package org.developer.study.springboot.exception;

import org.developer.study.springboot.dto.CommonStatusDto;
import org.developer.study.springboot.util.JsonUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/1/28.
 */
@Component
public class UnifyExcepionOutput implements  CommonExceptionInter {

    //异常输出的json格式作为response的返回内容
    public String responseExcepionContext(Throwable ex) {
        CommonStatusDto commonStatusDto = new CommonStatusDto();
        List<String> errorMessage = new ArrayList<String>();
        Integer code = null;

        if(ex instanceof  BizServiceException) {
            BizServiceException bizServiceException = (BizServiceException) ex;
            code = bizServiceException.getCode();
            errorMessage.add(ex.getMessage());
        }else {
            errorMessage.add("系统内部异常");
            code = HttpStatus.INTERNAL_SERVER_ERROR.value();
        }

        commonStatusDto.setSuccess(false);
        commonStatusDto.setCode(code);
        commonStatusDto.setErrorMessage(errorMessage);

        return JsonUtil.toJson(commonStatusDto);
    }

    //相应类型
    public MediaType responseExceptionType() {
        return MediaType.TEXT_PLAIN ;
    }
}
